package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    ArticleSearchService articleSearchService;
    @Autowired
    ApUserSearchService apUserSearchService;
    /**
     * ES文章分页搜索
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        //检查参数
        String searchWords = userSearchDto.getSearchWords();
        if (userSearchDto==null|| StringUtils.isBlank(searchWords)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //***如果是首页记录搜索关键字
        ApUser user = AppThreadLocalUtils.getUser();
        if (user !=null && userSearchDto.getFromIndex() == 0) {
            userSearchDto.setEntryId(user.getId());
            // 异步调用保存用户输入关键词记录
            apUserSearchService.insert( userSearchDto);
        }
        //构建查询执行查询
        SearchRequest searchRequest= new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建查询条件和过滤
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //关键词查询
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", searchWords);
        boolQueryBuilder.must(queryBuilder);

        //查询小于mindate的数据
        RangeQueryBuilder rangeQueryBuilder =
                QueryBuilders.rangeQuery("publishTime")
                        .lt(userSearchDto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);

        //分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(userSearchDto.getPageSize());

        //按照发布时间倒序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //高亮的三要素
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style=\"color:red\">");
        highlightBuilder.postTags("</font>");

        searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest ,RequestOptions.DEFAULT);

            //3 解析结果 封装结果
            SearchHits searchHits = searchResponse.getHits();
            List<Map> resultList = new ArrayList<>();
            // 总记录数
            long total = searchHits.getTotalHits().value;
            log.info("search result total:{}",total);
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                String jsonString = hit.getSourceAsString();
                Map apArticle = JSON.parseObject(jsonString, Map.class);

                // 获取高亮结果集
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                // 保留原始标题
                apArticle.put("o_title", apArticle.get("title"));
                String title = StringUtils.join(titles);
                if (StringUtils.isNotBlank(title)) {
                    apArticle.put("title", title);
                }

                resultList.add(apArticle);
            }

            return ResponseResult.okResult(resultList);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("search result error:{}",e);
        }



        return ResponseResult.errorResult(AppHttpCodeEnum.ERROR);
    }
}
